if(!this.troops) troops = {spear:"r",sword:"r",spy:"o",heavy:"o",catapult:"o"};
if(!this.maxPcnt) maxPcnt = 100;

var generalDefense = [15, 50, 10, 2, 30, 200, 20, 100, 250, 100, 15];
var cavalryDefense = [45, 15,  5, 1, 40,  80, 50,  50, 400,  50, 45];
var minimalGeneralDefense = 500000;
var minimalCavalryDefense = 500000;

var config = null;
var supportData = null;

var coordsReg  = /\s*\(?(\d+\|\d+)\)?\s*/i;
var excludeReg = /\s*(["Kdxy\|&=!\(\)\+\-\d<>]+(\s+["Kdxy\|&=!\(\)\+\-\d<>]+)*)\s*/;
var urlReg     = /[\?&]id=([^&#]*)/;
var countsReg  = /[\w ]+\s*(?:[\d:]+\s*)+\d+\/\d+/g;
var countReg   = /([\w ]+)\s*(?:[\d:]+\s*)+(\d+)\/(\d+)/;

var url  = window.location.href;
var host = window.location.host;
var vi   = game_data.village.id;
var nextLink    = "http://" + host + "/game.php?village=n" + vi + "&screen=place";
var recruitLink = "http://" + host + "/game.php?village=" + vi + "&screen=train";
var rallyLink   = "http://" + host + "/game.php?village=" + vi + "&screen=place";
var troopsLink  = "http://" + host + "/game.php?village=" + vi + "&screen=place&mode=units";

var doc = document;
if(window.frames.length > 0)
	doc = window.main.document;

function db(m) {
	if(console && console.debug)
		console.debug(m);
}

function d(v) {
	var X = v.split("|")[0];
	var Y = v.split("|")[1];
	var c = game_data.village.coord;
	var x = c.split("|")[0];
	var y = c.split("|")[1];
	return Math.sqrt((X - x) * (X - x) + (Y - y) * (Y - y));
}

function K(k) {
	var X = (k % 10);
	var Y = Math.floor(k / 10);
	var c = game_data.village.coord;
	var x = c.split("|")[0];
	var y = c.split("|")[1];
	return X == Math.floor(x / 100) && Y == Math.floor(y / 100);
}

function findTroopIDByName(name) {
	for(var id in config.units) {
		if(config.units[id].name == name) {
			return id;
		}
	}
	return null;
}

function readTroops() {
	var list = $("#train_form").text().match(countsReg);
	var supportCount = new Object();
	for(var n = 0; n < list.length; n++) {
		var m = list[n].match(countReg);
		if(m) {
			var id = findTroopIDByName(m[1]);
			if(id && troops[id]) {
				supportCount[id] = Math.floor(m[3] / 20);
			}
		}
	}
	
	var validDate = new Date();
	validDate.setDate(validDate.getDate() + 1);
	supportData.troopCount[vi] = supportCount;
	supportData.countValidUntil = validDate.getTime();
	localStorage.setItem('twPacketSupport', JSON.stringify(supportData));
}

function exceptionDecode(inp) {
	return $("<div/>").html(inp).text();
/*
	inp = inp.replace(/&lt;/g, "<");
	inp = inp.replace(/&gt;/g, ">");
	inp = inp.replace(/&amp;/g, "&");
	return inp;*/
}

function setTroops(counts, target) {
	var c = target.split("|");
	$("#units_form input[name=x]").val(c[0]);
	$("#units_form input[name=y]").val(c[1]);
	$("#target_attack").attr('disabled', 'disabled');
	
	var maxUnits = new Object();
	var troopcounts = supportData.troopCount[vi];
	var canSend = true;
	for(var id in troopcounts) {
		maxUnits[id] = eval($("#unit_input_" + id).next().html());
		if(troops[id] == "r" && troopcounts[id] > maxUnits[id] && troopcounts[id] * 20 * (1 - maxPcnt / 100) > maxUnits[id]) {
			canSend = false;
		}
	}
	
	if(canSend) {
		for(var id in troopcounts) {
			if(troopcounts[id] <= maxUnits[id]) {
				insertUnit($('#unit_input_' + id), troopcounts[id]);
			}
		}
		return true;
	}
	return false;
}

function processVillage() {	
	var c = game_data.village.coord;
	var x = c.split("|")[0];
	var y = c.split("|")[1];
	for(var n = 0; n < supportData.villages.length; n++) {
		var v = coordsReg.exec(supportData.villages[n]);
		if(v[1] == c) {
			if(!hideMessages) {
				alert("This village will recieve support, you don't have to send any.");
			}
			window.location = nextLink;
			return;
		}
	}
	for(var n = 0; n < supportData.keep.length; n++) {
		var v = coordsReg.exec(supportData.keep[n]);
		if(v[1] == c) {
			if(!hideMessages) {
				alert("This village is supported, you don't have to send any.");
			}
			window.location = nextLink;
			return;
		}
	}
	var errors = false;
	for(var n = 0; n < supportData.excludes.length; n++) {
		var e = false;
		try {
			e = eval(supportData.excludes[n]);
		} catch(err) {
			errors = true;
			db(supportData.excludes[n]);
			db(err.message);
		}
		if(e) {
			if(!hideMessages) {
				alert("This village is in the exclusion zone, you don't have to send any support right now.");
			}
			window.location = nextLink;
			return;
		}
	}
	if(errors) {
		alert("There are errors in the exceptions list");
	}
	
	var t = supportData.villages[supportData.index];
	/*while(d(t) > maxDistance) {
		t = supportData.villages[++supportData.index];
	}*/
	if(setTroops(supportData.troopCount, t)) {
		if(++supportData.index >= supportData.villages.length) {
			supportData.index = 0;
		}
		if(supportData.index == supportData.startIndex) {
			alert("You supported every village in the list. You're done now.");
		}
		localStorage.setItem('twPacketSupport', JSON.stringify(supportData));
	} else {
		if(!hideMessages) {
			alert("There is no more support in this village, going to the next.");
		}
		window.location = nextLink;
	}
}

function countSupport() {
	var troopList = $("input[name=all]").parent();
	var gd = 0;
	var cd = 0;
	var n = troopList.next();
	var m = 0;
	while(n && m < generalDefense.length) {
		var tc = n.text();
		gd += tc * generalDefense[m];
		cd += tc * cavalryDefense[m];
		m++;
		n = n.next();
	}

	if(gd >= minimalGeneralDefense && cd >= minimalCavalryDefense) {
		//create forum post 
	}
}

function getList(data, tagname) {
	var ind1 = data.indexOf('[' + tagname + ']');
	var ind2 = data.indexOf('[/' + tagname + ']');
	if (ind1 == -1 || ind2 == -1) {
		return null;
	}
	
	return data.substring(ind1 + tagname.length + 2, ind2).split('<br />');
}

function processForum(data) {
	excludeList = getList(data, "exclude");
	villageList = getList(data, "village_list");
	keepList    = getList(data, "supported_list");
	
	if(excludeList == null) {
		alert("The exclude list is not well formatted or none was found on the forum post.");
	}
	if(villageList == null) {
		alert("The village list is not well formatted or none was found on the forum post.");
	}
	if(keepList == null) {
		alert("The supported list is not well formatted or none was found on the forum post.");
	}
	
	var newList = new Array();
	var entry = excludeList.shift();
	while(entry != null) {
		var e = excludeReg.exec(exceptionDecode(entry));
		if(e != null) {
			newList.push(e[1]);
		}
		entry = excludeList.shift();
	}
	excludeList = newList;

	newList = new Array();
	var entry = villageList.shift();
	while(entry != null) {
		var r = coordsReg.exec(entry);
		if(r != null) {
			newList.push(r[1]);
		}
		entry = villageList.shift();
	}
	villageList = newList;

	newList = new Array();
	var entry = keepList.shift();
	while(entry != null) {
		var r = coordsReg.exec(entry);
		if(r != null) {
			newList.push(r[1]);
		}
		entry = keepList.shift();
	}
	keepList = newList;

	var validDate = new Date();
	validDate.setHours(validDate.getHours() + 6);
	
	supportData.startIndex     = Math.floor(Math.random() * villageList.length);
	supportData.index          = supportData.startIndex;
	supportData.excludes       = excludeList;
	supportData.villages       = villageList;
	supportData.keep           = keepList;
	supportData.listValidUntil = validDate.getTime();
	
	localStorage.setItem('twPacketSupport', JSON.stringify(supportData));
	processVillage();
}

function readForum() {
	var loc = urlReg.exec(url);
	$.get(config.urls.forum, {screen: "view_thread", thread_id: threadId}, processForum);
}

function main() {
	var supportString = localStorage.getItem('twPacketSupport');
	if(supportString) {
		supportData = JSON.parse(supportString);
	} else {
		supportData = {countValidUntil:0,listValidUntil:0,villages:[],keep:[],excludes:[],count:[],index:-1,startIndex:-1,troopCount:{}};
		localStorage.setItem('twPacketSupport', JSON.stringify(supportData));
	}
	
	if (url.indexOf('screen=train') != -1) {
		readTroops();
		window.location = rallyLink;
	} else if (url.indexOf('screen=place') != -1) {
		if(supportData.countValidUntil < new Date().getTime() || !supportData.troopCount[vi]) {
			window.location = recruitLink;
		} else {
			if(supportData.listValidUntil < new Date().getTime()) {
				readForum();
			} else {
				processVillage();
			}
		}
	} else {
		if(supportData.countValidUntil < new Date().getTime()) {
			window.location = recruitLink;
		} else {
			window.location = rallyLink;
		}
	}
	
	return false;
}

function loadSettings() {
	config = new Config();
	config.onloaded = function() {
		main();
	};
	config.load();
}

function initSettings() {
	var configString = localStorage.getItem('twConfig');
	if(configString && configString.length > 0) {
		config = JSON.parse(configString);
	}
	if(config == null || !config.time || (new Date().getTime() - config.time) > 1000 * 3600 * 24 * 7) {
		$.getScript(scriptRoot+"settings.js", loadSettings);
	} else {
		main();
	}
}

initSettings();